#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "g726.h"

static uint32_t get_file_size(char *file_name)
{
    struct stat buf;
    if(stat(file_name, &buf) < 0)
    {
        return 0;
    }
    return (uint32_t)buf.st_size;
}

int main(int argc, char **argv)
{
    int ret = 0;
    int16_t ival = 0;
    uint8_t oval = 0;
    int size  = 0;
    int index = 0;
	int bitCount = 0;
    

    char        iname[32];
    FILE       *ifile       = NULL;
    uint8_t    *ibuf        = NULL;
    uint32_t    isize       = 0;
    int         ircnt       = 0;

    char        oname[32];
    FILE       *ofile       = NULL;
    uint8_t    *obuf        = NULL;
    uint32_t    osize       = 0;
    int         owcnt       = 0;

    if (argc != 4)
    {
        printf("usage: %s <bitCount> <g726> <pcm>\n", argv[0]);
        printf("eg   : %s 2 xxx.g726 xxx.pcm\n", argv[0]);
        printf("\n");
        return -1;
    }

    bitCount = atoi(argv[1]);
    printf("bitCount     = %d\n", bitCount);

	if(bitCount < 2 || bitCount > 5) {
		printf("bitcount only support 2 - 5\n");
		return -1;
	}

    strcpy(iname, argv[2]);
    strcpy(oname, argv[3]);
    printf("iname    = %s\n", iname);
    printf("oname    = %s\n", oname);

    isize = get_file_size(iname);
    osize = isize / bitCount * 16;
    printf("isize    = %d\n", isize);
    printf("osize    = %d\n", osize);

    ibuf = (uint8_t *)malloc(isize);
    obuf = (uint8_t *)malloc(osize);
    memset(ibuf, 0, isize);
    memset(obuf, 0, osize);

    ifile = fopen(iname, "r");

    ircnt = fread(ibuf, 1, isize, ifile);
    fclose(ifile);

    g726_state_t *handle = malloc(sizeof(g726_state_t));
    g726_init(handle, 8000 * bitCount);
	ret = g726_decode(handle, (short *)obuf, ibuf, ircnt);

	if(ret*2 != osize) {
		printf("decode output size:%d is not the rigth size:%d\n",ret,osize);
	}

    ofile = fopen(oname, "wb");
    owcnt = fwrite(obuf, 1, osize, ofile);
    fclose(ofile);
    
    free(handle);

    free(ibuf);
    free(obuf);

    printf("G.726 %d decode finish!\n",bitCount);

    return 0;
}




